from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.template import Context, loader
from django.shortcuts import render_to_response

from google.appengine.api import users


import json,logging,urllib

from django.core import serializers


import time


from home.models import Note

def update(request):
    
  user = users.get_current_user()
  if user:
    nickname = user.email()
    noteContent = request.REQUEST.get('note', '');
    logging.info("update notes:%S",note);
    note = Note(notePoster=nickname,noteContent=noteContent);
    note.put();
    logging.info("post stored");
    
  else:
    logging.warn("Invalid update request from %s",request.get_host())
    
#def retrieveNotes(request)
def data(request):
  results = Note.all()
  notesCount = results.count()  
  notesContent = serializers.serialize("json",results);
  logging.info("Raw record:%s",notesContent);
  r = json.loads(notesContent);
  notesContent = r[0]['fields'];
  r = json.loads(json.dumps(notesContent))
  user = users.get_current_user()  
  gmail = ""
  nickname = ""
  if user:
      gmail= user.email()
      nickname = user.nickname()
      sign_url = users.create_logout_url("/")
  else:
      sign_url = users.create_login_url("/")  
  r['notesCount']=notesCount
  r['gmail']=gmail
  r['sign_url']=sign_url
  data =  json.dumps(r) 
  logging.info( data ); 
  return HttpResponse(data);
  
    
def data2(request):
  user = users.get_current_user()  
  gmail = ""
  nickname = ""
  if user:
      gmail= user.email()
      nickname = user.nickname()
      sign_url = users.create_logout_url("/")
  else:
      sign_url = users.create_login_url("/")
      
  #sign_url = urllib.urlencode(sign_url)
  #test css stick footer code ,which will exceed 100% of screeen display	 
  #data = json.dumps({'gmail': gmail,'sign_url':sign_url,'nickname':nickname,})
  logging.info("sign_url=%s",sign_url)
  
  data = json.dumps([{'gmail': gmail},{'sign_url': sign_url},])
  logging.info('Json data to client:%s',data)
  return HttpResponse(data+""+notesContent);


def index(request):
  return HttpResponseRedirect('www/h/Home.html')


	

def index2(request):
  user = users.get_current_user()  
  gmail = ""
  nickname = ""
  if user:
    gmail= user.email()
    nickname = user.nickname()
    sign_url = users.create_logout_url("/")
  else:
    sign_url = users.create_login_url("/")	
  #test css stick footer code ,which will exceed 100% of screeen display	 
  list = [1];
  for i in range(1,1):
      i=i+1;
      list.append(i);
  return render_to_response('home/index.html', {'gmail': gmail,'sign_url':sign_url,'nickname':nickname,'list':list})


	
	
